import json5
import json

SIGNING_TEMPLATE = {
    "name": "default",
    "type": "HarmonyOS",
    "material": {}
}

SIGNING_MODULE = {
    'debug': 'default',
    'release': 'public',
}

OH_PACKAGE_JSON = '/oh-package.json5'
ENTRY_BUILD_PROFILE = '/entry/build-profile.json5'

def addDependencies(projectPath, dependencies):
    if len(dependencies) > 0:
        if isinstance(dependencies, str):
            dependenciesList = json5.loads(dependencies)
            if len(dependenciesList):
                print(f'data_dependencies:{dependenciesList}')
                changeOhPackage(projectPath,dependenciesList)
                changeEntryBuildProfile(projectPath,dependenciesList)
            else:
                print(f"暂无数据，无需添加")
        else:
            print(f"模块数据格式错误，请检查")
    else:
        print(f"暂无数据，无需添加")
def changeOhPackage(projectPath,dependenciesList):
    with open(f"{projectPath}{OH_PACKAGE_JSON}", 'r') as f:
        data = json5.load(f)
        print(data)
        dependenciesMap =  {}
        for item in dependenciesList:
            print(f"item:{item}")
            dependenciesMap[item["name"]] = item["version"]
        data['dependencies'] = {**data['dependencies'], **dependenciesMap}
        print(f"dependencies:{data['dependencies']}")
        with open(f"{projectPath}{OH_PACKAGE_JSON}", 'w') as f: json.dump(data, f, indent=2)


def changeEntryBuildProfile(projectPath, dependenciesList):
    with open(f"{projectPath}{ENTRY_BUILD_PROFILE}", 'r') as f:
        data = json5.load(f)
        packagesList = []
        for item in dependenciesList:
            packagesList.append(item["name"])
        recursionCreate(data)
        packages = data['buildOption']['arkOptions']['runtimeOnly']['packages']
        packages.extend(packagesList)
        print(packages)
        with open(f"{projectPath}{ENTRY_BUILD_PROFILE}", 'w') as f: json.dump(data, f, indent=2)

def recursionCreate(data):
    if 'buildOption' in data:
        if 'arkOptions' in data['buildOption']:
            if 'runtimeOnly' in data['buildOption']['arkOptions']:
                if not 'packages' in data['buildOption']['arkOptions']['runtimeOnly']:
                    data['buildOption']['arkOptions']['runtimeOnly']['packages'] = []
                    recursionCreate(data)
            else:
                data['buildOption']['arkOptions']['runtimeOnly'] = {}
                recursionCreate(data)
        else:
            data['buildOption']['arkOptions'] = {}
            recursionCreate(data)
    else:
        data['buildOption'] = {}
        data['buildOption']['arkOptions'] = {}
        data['buildOption']['arkOptions']['runtimeOnly'] = {}
        data['buildOption']['arkOptions']['runtimeOnly']['packages'] = []

